var express = require('express')
var history = require('connect-history-api-fallback')
var app = express()
var server = require('http').Server(app)
var io = require('socket.io')(server)
// 解析post请求
var bodyParser = require('body-parser')
app.use(
  bodyParser.urlencoded({
    extended: true
  })
)
app.use(bodyParser.json())
// mongoose框架
var mongoose = require('mongoose')
// jsonwebtoken
var jwt = require('jsonwebtoken')
var request = require('request')
//上传图片multer
var multer = require('multer')
// 文件读取模块
var fs = require('fs')
//将文件设置成静态
app.use('/public', express.static('public'))
// 绑定history
// app.use(history({
//   verbose: true,
//   index: '/'
// }))
// var path = require('path')
// app.get("/", function (req, res) {
//   res.sendFile(path.join(__dirname, "dist/index.html"))
// })
// 查询字符串
var querystring = require('querystring')
// 图片验证码库
var svgCaptcha = require('svg-captcha')
// 获取邮件验证码库
var nodemailer = require('nodemailer')
// 获取数据库模型
require('./bds/models/chat.js')
// node实现跨域
var cors = require('cors')
app.use(cors())
// 拦截所有请求判断是否有token authorization
app.all('/*', (req, res, next) => {
  // 白名單
  const whiteList = ['/login', '/upload', '/register', '/email', '/mobile', '/captcha']
  // 判断是否是白名单的路径
  var hasOneOfpath = (url, arr) => {
    return arr.some(function (item) {
      return item.includes(url);
    })
  };
  // 是白名单可以直接访问不是就验证token
  if (hasOneOfpath(req.url, whiteList)) {
    next();
  } else {
    try {
      var decoded = jwt.verify(req.headers.token, 'myToken');
      console.log(decoded)
      next()
      return
    } catch (err) {
      // err
      res.json({
        status: 4000,
        msg: 'token过期请重新登录'
      })
      return
    }
  }
})
require('./module/user/register')(app, mongoose)
// 登录组件
require('./module/user/login')(app, mongoose, jwt)
// 登录文图验证码
require('./module/user/captcha')(app, svgCaptcha)
// 获取短信验证码
require('./module/user/mobile')(app, querystring, request)
// 获取邮箱验证码
require('./module/user/email')(app, nodemailer)
// websocket库
require('./module/socket')(app, io, mongoose)
// 直播JS
// require('./module/live/callback')(app, io)
// 新建患者信息
require('./module/patient/create')(app, mongoose)
// 搜索患者信息
require('./module/patient/search')(app, mongoose)
// 患者状态
require('./module/patient/state')(app, mongoose)
// 患者住院
require('./module/patient/sick')(app, mongoose)
// 来源统计
require('./module/patient/statistics')(app, mongoose)
// 更新来源
require('./module/patient/updata')(app, mongoose)
// 编辑数据
require('./module/patient/edit')(app, mongoose)
//创建员工
require('./module/staff/create')(app, mongoose)
//获取员工
require('./module/staff/status')(app, mongoose)
//上传头像
require('./module/staff/upload')(app, mongoose, multer, fs)
// 访问8080端口
server.listen(8080, function (res, req) {
  console.log('http://192.168.16.112:8080')
})
